package net.hky365.lowcode.magic;

import lombok.extern.slf4j.Slf4j;
import net.hky365.shop.framework.common.exception.enums.GlobalErrorCodeConstants;
import net.hky365.shop.framework.common.pojo.CommonResult;
import net.hky365.shop.framework.common.pojo.ResultMessage;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.ssssssss.script.exception.MagicScriptException;

@Slf4j
@ControllerAdvice
public class MagicErrorHandler {
    /**
     * magic 脚本异常捕获, 若是result 类型异常则直接返回消息
     */
    @ResponseBody
    @ExceptionHandler(value = MagicScriptException.class)
    public CommonResult<Object> apiException(MagicScriptException e) {
        if (e.getCause() instanceof ResultMessage) {
            log.debug("MagicScriptException =====>> ", e);
            ResultMessage fe = (ResultMessage) e.getCause();
            return CommonResult.error(fe);
        } else {
            log.error("MagicScriptException =====>> ", e);
            return CommonResult.error(GlobalErrorCodeConstants.UNKNOWN);
        }
    }
}
